package main

import (
	"fmt"
	"gitee.com/fanchenggang/SecKill/proxy/service"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"strings"
)

var (
	secKillConf = &service.SecKillConf{
		SecProductInfoMap: make(map[int]*service.SecProductInfoConf, 1024),
	}
)

func initConfig() error {
	redisBlackAddr := beego.AppConfig.String("redis_black_addr")
	etcdAddr := beego.AppConfig.String("etcd_addr")
	if len(redisBlackAddr) == 0 || len(etcdAddr) == 0 {
		return fmt.Errorf("init config failed, redis or etcd config is null")
	}
	logs.Debug("read config success,redis addr:%v", redisBlackAddr)
	logs.Debug("read config success,etcd addr:%v", etcdAddr)

	secKillConf.RedisBlackConf.Addr = redisBlackAddr
	secKillConf.RedisBlackConf.MaxIdle, _ = beego.AppConfig.Int("redis_black_max_idle")
	secKillConf.RedisBlackConf.MaxActive, _ = beego.AppConfig.Int("redis_black_max_active")
	secKillConf.RedisBlackConf.IdleTimeout, _ = beego.AppConfig.Int("redis_black_idle_timeout")

	secKillConf.EtcdConf.Addr = etcdAddr
	secKillConf.EtcdConf.TimeOut, _ = beego.AppConfig.Int("etcd_timeout")
	secKillConf.EtcdConf.SecKeyPrefix = beego.AppConfig.String("etcd_sec_key_prefix")
	secKillConf.EtcdConf.SecProductKey = fmt.Sprintf("%s/%s", secKillConf.EtcdConf.SecKeyPrefix, beego.AppConfig.String("etcd_product_key"))

	secKillConf.LogPath = beego.AppConfig.String("log_path")
	secKillConf.LogLevel = beego.AppConfig.String("log_level")

	secKillConf.CookieSecretKey = beego.AppConfig.String("cookie_secret_key")
	secKillConf.UserSecAccessLimit, _ = beego.AppConfig.Int("user_sec_access_limit")

	referList := beego.AppConfig.String("refer_white_list")
	if len(referList) > 0 {
		secKillConf.ReferWhiteList = strings.Split(referList, ",")
	}

	secKillConf.IPSecAccessLimit, _ = beego.AppConfig.Int("ip_sec_access_limit")

	secKillConf.RedisProxy2LayerConf = secKillConf.RedisBlackConf

	secKillConf.WriteProxy2LayerGoroutineNum, _ = beego.AppConfig.Int("write_proxy2layer_goroutine_num")
	secKillConf.ReadLayer2ProxyGoroutineNum, _ = beego.AppConfig.Int("read_layer2proxy_goroutine_num")

	return nil

}
